package org.springblade.modules.admin.task;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springblade.common.mq.MqMessageService;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.entity.MaintainPlanContent;
import org.springblade.modules.admin.enums.TaskStatusEnum;
import org.springblade.modules.admin.service.IMaintainMalfunctionRescueService;
import org.springblade.modules.admin.vo.MapUserInfoDetailVO;
import org.springblade.modules.admin.vo.RescueOrderDetail;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description 救援消息job
 * @Author ysq
 * @Date 2023/6/21
 **/
@Component
public class RescueMessageJob {

	@Resource
	private MqMessageService mqMessageService;
	@Resource
	private IMaintainMalfunctionRescueService maintainMalfunctionRescueService;
	@Resource
	private Environment environment;

	/**
	 * 定时任务：1分钟一次
	 */
	//@Scheduled(cron = "1 * * * * ?")
	@XxlJob(value = "send")
	public void send() {
		XxlJobHelper.handleSuccess("救援消息推送-(send)-[执行]开始");
		try {
			String curEnvironment = environment.getActiveProfiles()[0];
			if (Func.equalsSafe(curEnvironment, "dev")) {
				return;
			}
			List<RescueOrderDetail> rescueList = maintainMalfunctionRescueService.rescueDetailList();
			for (RescueOrderDetail rescueOrderDetail : rescueList) {
				List<MapUserInfoDetailVO> rescueUsers = maintainMalfunctionRescueService.mapUserDetails(rescueOrderDetail.getPlanId());
				rescueOrderDetail.setMapUserInfoDetails(rescueUsers);
				// 再次确认状态无变更,再推送
				MaintainPlanContent maintainPlanContent = maintainMalfunctionRescueService.getMaintainPlanById(rescueOrderDetail.getPlanId());
				if (Func.isNotEmpty(maintainPlanContent) && Func.equalsSafe(maintainPlanContent.getStatus(), TaskStatusEnum.JY_PROCESSED.getStatus())) {
					mqMessageService.send(JSONObject.toJSONString(rescueOrderDetail, SerializerFeature.WRITE_MAP_NULL_FEATURES));
				}
			}
			XxlJobHelper.handleSuccess("救援消息推送-(send)-[执行]成功");

		}catch (Exception e){
			XxlJobHelper.handleSuccess("救援消息推送-(send)-[执行]失败"+e);

		}

	}
}
